package com.zl.gmadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.google.common.collect.Collections2;
import com.zl.gmadmin.entity.SysDict;
import com.zl.gmadmin.entity.SysDictDetail;
import com.zl.gmadmin.exception.BaseException;
import com.zl.gmadmin.mapper.SysDictDetailsMapper;
import com.zl.gmadmin.mapper.SysDictMapper;
import com.zl.gmadmin.payload.DictQueryCriteria;
import com.zl.gmadmin.service.SysDictService;
import com.zl.gmadmin.utils.Builder;
import com.zl.gmadmin.utils.JsonUtil;
import com.zl.gmadmin.utils.LogUtil;
import com.zl.gmadmin.utils.PageUtils;
import com.zl.gmadmin.vo.DictDetatilsVo;
import io.jsonwebtoken.lang.Collections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/4/12 11:36
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    private final SysDictMapper sysDictMapper;

    private final SysDictDetailsMapper sysDictDetailMapper;

    public SysDictServiceImpl(SysDictMapper sysDictMapper, SysDictDetailsMapper sysDictDetailMapper) {
        this.sysDictMapper = sysDictMapper;
        this.sysDictDetailMapper = sysDictDetailMapper;
    }


    @Override
    public List<DictDetatilsVo> findDictByName(DictQueryCriteria criteria) {

        List<SysDict> sysDicts = sysDictMapper.findDictByName(criteria.getDictName());

        List<DictDetatilsVo> dictDetatilsVos = new ArrayList<>();
        for (SysDict d : sysDicts
        ) {
            for (SysDictDetail dd : d.getDictDetailList()
            ) {
                DictDetatilsVo dictDetatilsVo = Builder.of(DictDetatilsVo::new)
                        .with(DictDetatilsVo::setId, dd.getDetailId())
                        .with(DictDetatilsVo::setDictSort, dd.getDictSort())
                        .with(DictDetatilsVo::setLabel, dd.getLabel())
                        .with(DictDetatilsVo::setSysDict, d)
                        .with(DictDetatilsVo::setValue, dd.getValue())
                        .build();
                dictDetatilsVos.add(dictDetatilsVo);
            }
        }

        return dictDetatilsVos;
    }

    @Override
    public Map<String, Object> getDictByPage(DictQueryCriteria dictQueryCriteria, Page<SysDict> sysDictPage) {
        QueryWrapper<SysDict> wrapper = new QueryWrapper<>();

        IPage<SysDict> iPage = sysDictMapper.selectDictAndDetailsPage(sysDictPage, wrapper);
        List<SysDict> sysDicts = iPage.getRecords();


        return PageUtils.toPage(sysDicts, iPage.getTotal());
    }

    @Transactional(rollbackFor = BaseException.class)
    @Override
    public void saveDict(SysDict sysDict) {
        sysDictMapper.insert(sysDict);
        if (Objects.nonNull(sysDict.getDictDetailList())&&sysDict.getDictDetailList().size() > 0) {
            sysDict.getDictDetailList().forEach(sysDictDetail -> {
                sysDictDetail.setDictId(sysDict.getId());
                sysDictDetailMapper.insert(sysDictDetail);
            });
        }
    }

    @Override
    public void updateDictById(SysDict sysDict) {
        LogUtil.debug("更新测试");
        LogUtil.debug(JsonUtil.toJsonStr(sysDict));
        sysDictMapper.updateById(sysDict);


        QueryWrapper<SysDictDetail> sysDictDetailQueryWrapper=new QueryWrapper<>();
        sysDictDetailQueryWrapper.eq("dict_id",sysDict.getId());
        if (Objects.nonNull(sysDict.getDictDetailList())&&sysDict.getDictDetailList().size()>0){
            //如果存在值，先删除，在插入 ,如果判断需要多加逻辑
            sysDictDetailMapper.delete(sysDictDetailQueryWrapper);
            sysDict.getDictDetailList().forEach(sysDictDetail -> {
                sysDictDetail.setDictId(sysDict.getId());
                sysDictDetailMapper.insert(sysDictDetail);
            });
        }else {
            sysDictDetailMapper.delete(sysDictDetailQueryWrapper);
        }

    }

    @Transactional(rollbackFor = BaseException.class)
    @Override
    public void deleteDictByIds(List<Long> ids) {
//        先删除子表
        ids.forEach(id -> {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("dict_id", id);
           List<SysDictDetail> sysDictDetail = sysDictDetailMapper.selectList(queryWrapper);
            if (!Collections.isEmpty(sysDictDetail)) {

                sysDictDetailMapper.deleteBatchIds(sysDictDetail.stream().map(sd->sd.getDetailId()).collect(Collectors.toList()));
            }
        });
        sysDictMapper.deleteBatchIds(ids);
    }
}
